package com.shambles.weixin.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.shambles.manage.mapper.PhotoMapper;
import com.shambles.manage.mapper.UsersMapper;
import com.shambles.manage.model.Photo;
import com.shambles.manage.model.Users;
import com.shambles.manage.model.dto.SubScribeDTO;
import com.shambles.manage.model.dto.SubscribeDetailDTO;
import com.shambles.manage.model.dto.TwoDTO;
import com.shambles.manage.model.dto.TwoIntDTO;
import com.shambles.manage.model.entity.BasePage;
import com.shambles.manage.model.entity.MessageRequestVM;
import com.shambles.manage.model.entity.RestResponse;
import com.shambles.manage.service.BoothService;
import com.shambles.manage2.dto.SysUserDTO;
import com.shambles.manage2.tkmapper.entity.*;
import com.shambles.manage2.tkmapper.mapper.*;
import com.shambles.manage2.utils.CommonUtils;
import com.shambles.manage2.utils.PageUtils;
import org.apache.commons.collections.ListUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/mobile/booth")
public class BoothController {

    @Resource
    private BoothService boothService;
    @Resource
    private SubscribeDetailMapper subscribeDetailMapper;
    @Resource
    private UsersinfoMapper usersinfoMapper;
    @Resource
    private CattleMapper cattleMapper;
    @Autowired
    private PhotoMapper photoMapper;
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private CostDetailMapper costDetailMapper;

    /**
     * 返回全部的摊位信息
     */
    @RequestMapping("showBooth")
    @ResponseBody
    public RestResponse showBooth(Integer pageIndex, Integer pageSize) {
        MessageRequestVM messageRequestVM = new MessageRequestVM();
        messageRequestVM.setPageIndex(pageIndex);
        messageRequestVM.setPageSize(pageSize);
        PageInfo<AbattoirBooth> pageInfo = boothService.findAllBooth(messageRequestVM);
        return RestResponse.ok(pageInfo);
    }

    /**
     * 返回空置的摊位信息
     */
    @RequestMapping("showEmptyBooth")
    @ResponseBody
    public RestResponse showEmptyBooth(Integer pageIndex, Integer pageSize) {
        MessageRequestVM messageRequestVM = new MessageRequestVM();
        messageRequestVM.setPageIndex(pageIndex);
        messageRequestVM.setPageSize(pageSize);
        PageInfo<AbattoirBooth> pageInfo = boothService.findEmptyBooth(messageRequestVM);
        return RestResponse.ok(pageInfo);
    }

    /**
     * 个人屠宰记录
     */
    @RequestMapping("slaughter")
    @ResponseBody
    public RestResponse slaughter(HttpServletRequest request, Integer pageIndex, Integer pageSize) {
        //预约人的openID
        String openId = (String) request.getSession().getAttribute("openId");
        //根据openID拿到姓名
        Usersinfo usersinfo = usersinfoMapper.findByOpenID(openId);
        if (usersinfo.getName() == null) {
            return RestResponse.fail(504, "请先注册");
        }
        MessageRequestVM messageRequestVM = new MessageRequestVM();
        messageRequestVM.setPageIndex(pageIndex);
        messageRequestVM.setPageSize(pageSize);
        messageRequestVM.setName(usersinfo.getName());
        PageInfo<Cost> pageInfo = boothService.slaughter(messageRequestVM);
        List<Cost> list = pageInfo.getList();
        for (Cost cost : list) {
            String guid = cost.getGuid();
            //根据costGuid，costDetails查询
            List<CostDetail> costDetails = costDetailMapper.findByGuid(guid);
            cost.setCostDetails(costDetails);
        }
        return RestResponse.ok(pageInfo);
    }

    /**
     * 屠宰种类
     */
    @RequestMapping("kind")
    @ResponseBody
    public RestResponse kind() {
        List<String> list = boothService.kind();
        return RestResponse.ok(list);
    }

    /**
     * 查询预约表是否时间有冲突
     */
    @RequestMapping("subscribe")
    @ResponseBody
    public RestResponse subscribe(String time, int id) {
        SimpleDateFormat slf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (time != null) {
            Date parse = null;
            try {
                parse = slf.parse(time);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            SubScribeDTO subScribeDTO = new SubScribeDTO();
            subScribeDTO.setTime(parse);
            subScribeDTO.setId(id);
            AbattoirBooth abattoirBooth = boothService.findSubscribe(subScribeDTO);
            if (abattoirBooth == null) {
                return RestResponse.ok();
            } else {
                return RestResponse.fail(504, "预约失败");
            }
        } else {
            return RestResponse.fail(504, "时间不能为空");
        }
    }


    /**
     * 信息写入预约信息表
     */
    @RequestMapping("insertSub")
    @ResponseBody
    public RestResponse insertSub(HttpServletRequest request, String detailDTOS, String time, String check_id) throws JSONException {
        long start = System.currentTimeMillis();
        List<SubscribeDetailDTO> subscribeDetailDTOS = JSONArray.parseArray(detailDTOS, SubscribeDetailDTO.class);
        System.out.println(detailDTOS);
        //判断是否达到屠宰上限
        Integer upperLimit = 0;
        try {
            upperLimit = subscribeDetailMapper.findUpperLimit();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (upperLimit >= 2000) {
            return RestResponse.fail(504, "屠宰数量达到上限，无法预约");
        }

        //预约人的openID
        String openId = (String) request.getSession().getAttribute("openId");
        //通过openID找到信息
        Usersinfo user = boothService.findByOpenID(openId);
        SubscribeInformation information = new SubscribeInformation();
        SimpleDateFormat slf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date parse = null;
        try {
            parse = slf.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long parseTime = parse.getTime();
        //预约人预约时间
        information.setSubscribeTime(parseTime);
        //预约人openID
        information.setSubscribeOpenId(openId);
        //预约人姓名
        information.setSubscribeName(user.getName());
        //设置当前时间
        information.setCurrentTimeNow(new Date().getTime());
        //待审核   预约状态
        information.setStatus(0);
        //设置预约guid
        String simpleUUID = IdUtil.simpleUUID();
        information.setGuid(simpleUUID);
        //更新图片guid
        TwoIntDTO twoIntDTO = new TwoIntDTO();
        twoIntDTO.setCheck_id(check_id);
        twoIntDTO.setSimpleUUID(simpleUUID);
        int update = photoMapper.updateByGuid(twoIntDTO);
        //查询图片地址放到list

        //存信息到subscribeDetail / information
        List<SubscribeDetail> details = new ArrayList<>();
        for (SubscribeDetailDTO detailDTO : subscribeDetailDTOS) {
            SubscribeDetail subscribeDetail = new SubscribeDetail();
            subscribeDetail.setType(detailDTO.getTy());
            subscribeDetail.setNumber(detailDTO.getSize());
            subscribeDetail.setSubscribeGuid(simpleUUID);    //存预约guid
            subscribeDetail.setGuid(IdUtil.simpleUUID());   //设置自身guid
            //根据种类名设置种类guid
            String cattleGuid = cattleMapper.findByType(detailDTO.getTy());
            subscribeDetail.setCattleGuid(cattleGuid);
            details.add(subscribeDetail);
        }
        int i = boothService.insertSub(information, details,user.getName());
        //返回管理员的openID
//        List<String> openIds = sysUserMapper.findCheckOK();
        List<String> openIds = usersMapper.findCheckOK();
        //列出所有类型
        List<String> list = new ArrayList<>();
        for (SubscribeDetail subscribeDetail : details) {
            String type = subscribeDetail.getType();
            list.add(type);
        }
        if (i > 0) {
            //发送通知
            try {
                Runnable r = new Runnable() {
                    @Override
                    public void run() {
                        WechatSendMessageController wechatSendMessageController = new WechatSendMessageController();
                        //兴泸信息
                        //nIGv61NrzkPh4tj0JmoReprV-IfDr4WTf2VRC-GSl0o
                        for (String id : openIds) {     //发送消息给每一个合格的管理员（只有存有openID在数据库的管理才合格）
                            Integer res = wechatSendMessageController.sendMessage2(id, "RQ19HPKzoJCXlTlXblCjJLEdzTOJPRjuIc3RckVwwsw", "预约提醒", "http://www.longtengkonggu.com/shambles/mobile/asset/myTask.html",
                                    "您有新的预约通知", list.toString(), time, user.getName(), user.getPhone(), "");
                        }
                    }
                };
                Thread t = new Thread(r);
                t.start();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("time-------------"+(end-start));
        return RestResponse.ok();
    }

    /**
     * 设置管理员
     */
    @RequestMapping("setManage")
    @ResponseBody
//    public RestResponse setManage(@RequestParam("id")Integer id,@RequestParam("status")Integer status){
    public RestResponse setManage(@RequestBody JSONObject jsonObject) {
        Integer id = jsonObject.getInteger("id");
        Integer status = jsonObject.getInteger("status");
        TwoDTO twoDTO = new TwoDTO();
        twoDTO.setId(id);
        twoDTO.setStatus(status);
        usersMapper.updateUserByStatus(twoDTO);
        return RestResponse.ok();
    }

    /**
     * 返回所有管理员
     */
    @RequestMapping("returnAllUsers")
    @ResponseBody
    public RestResponse returnAllUsers(@RequestBody JSONObject jsonObject) {
        Integer pageIndex = jsonObject.getInteger("pageIndex");
        Integer pageSize = jsonObject.getInteger("pageSize");
//        MessageRequestVM messageRequestVM = new MessageRequestVM();
//        messageRequestVM.setPageIndex(pageIndex);
//        messageRequestVM.setPageSize(pageSize);
        BasePage basePage = new BasePage();
        basePage.setPageIndex(pageIndex);
        basePage.setPageSize(pageSize);
        PageInfo<Users> pageInfo = boothService.returnAllUsers(basePage);
        List<Users> users = usersMapper.returnAllUsers();   //所有数据
        List<Users> usersList = PageUtils.convert(users, pageIndex, pageSize);
        List<Users> list = pageInfo.getList();
        list.clear();
        for (Users users1 : usersList) {
            list.add(users1);
        }
        pageInfo.setTotal(list.size());
        return RestResponse.ok(pageInfo);
    }


    /**
     * 预约人的查看自己的检疫证明
     */
    @RequestMapping("findSimple")
    @ResponseBody
    public RestResponse findSimple(HttpServletRequest request, @RequestParam String check_id) {
        System.out.println("1");
        List<Photo> list = boothService.findSimple(check_id);
        List<String> addressUrl = new ArrayList<>();
        for (Photo photo : list) {
            String imageUrl = photo.getImageUrl();
            addressUrl.add(imageUrl);
        }
        return RestResponse.ok(addressUrl);
    }

    /**
     * 审核预约发给管理后台,后台展示预约数据
     */
    @RequestMapping("checkSubscribe")
    public @ResponseBody
    RestResponse checkSubscribe( @RequestParam("pageIndex") Integer pageIndex, @RequestParam("pageSize") Integer pageSize, @RequestParam("status") Integer status) throws JSONException {
        MessageRequestVM messageRequestVM = new MessageRequestVM();
        messageRequestVM.setPageIndex(pageIndex);
        messageRequestVM.setPageSize(pageSize);
        PageInfo<SubscribeInformation> pageInfo = null;
        if(status == 9){
            pageInfo = boothService.findAllSubscribe(messageRequestVM);
        }else {
            messageRequestVM.setStatus(status);
            pageInfo = boothService.findCheckSubscribe(messageRequestVM);

        }
        List<SubscribeInformation> list = pageInfo.getList();
        for (SubscribeInformation information : list) {
            List<String> list1 = photoMapper.findBySecGuid(information.getGuid());
            information.setImagesUrl(list1);
            String guid = information.getGuid();        //预约表的GUID
            List<SubscribeDetail> details = subscribeDetailMapper.findBySubGuid(guid);
            information.setDetails(details);
            String subscribeOpenId = information.getSubscribeOpenId();  //预约人的openid
            Usersinfo usersinfo = usersinfoMapper.findByOpenID(subscribeOpenId);
            information.setPhone(usersinfo.getPhone());
        }
        return RestResponse.ok(pageInfo);
    }


    /**
     * 拒绝或同意申请
     * @param id    预约表的自增id
     * @param status    对应预约表的place
     * @return
     * @throws JSONException
     */
    @RequestMapping("dearSubscribe")
    public @ResponseBody
    RestResponse dearSubscribe(HttpServletRequest request,@RequestParam("id") Integer id, @RequestParam("status") Integer status) throws JSONException {
//        SysUserDTO currentUser = CommonUtils.getCurrentUser();//操作人
        //操作人的openID
        String openId = (String) request.getSession().getAttribute("openId");
        //操作人姓名
        Usersinfo usersinfo = usersinfoMapper.findByOpenID(openId);
        String name = "";
        if(usersinfo != null){
            name = usersinfo.getName(); //操作人
        }
        //根据id添加操作人到当条数据
        boothService.updateById(id,name);
        SubscribeInformation information = boothService.findOpenIdByID(id); //根据id返回对象
        SimpleDateFormat slf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(information.getSubscribeTime());
        if (status == 1) {    //审核通过
            int i = boothService.deal(id, status);
            if (i > 0) {
                //发送通知
                try {
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            WechatSendMessageController wechatSendMessageController = new WechatSendMessageController();
                            //nIGv61NrzkPh4tj0JmoReprV-IfDr4WTf2VRC-GSl0o
                            Integer res = wechatSendMessageController.sendMessage2(information.getSubscribeOpenId(), "KIPU6_LROddfXN3WT7CpxHfL3DNzoyH0mrhhSM_srms", "预约提醒", "",
                                    "尊敬的"+information.getSubscribeName()+"您好，您的审核已通过", "预约申请", "请在预约时间:" + slf.format(date) + "到龙驰屠宰家禽场进行屠宰", "审核通过", "", "");
                        }
                    };
                    Thread t = new Thread(r);
                    t.start();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            return RestResponse.ok();
        } else {      //审核不通过
            int i = boothService.deal(id, status);
            if (i > 0) {
            //发送通知
                try {
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            WechatSendMessageController wechatSendMessageController = new WechatSendMessageController();
                            //nIGv61NrzkPh4tj0JmoReprV-IfDr4WTf2VRC-GSl0o
                            Integer res = wechatSendMessageController.sendMessage2(information.getSubscribeOpenId(), "KIPU6_LROddfXN3WT7CpxHfL3DNzoyH0mrhhSM_srms", "预约提醒", "",
                                    "尊敬的"+information.getSubscribeName()+"您好，您的审核未通过", "预约申请", "您的预约时间:" + slf.format(date), "审核未通过", "", "");
                        }
                    };
                    Thread t = new Thread(r);
                    t.start();
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
            return RestResponse.ok();
        }
    }
}
